using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace sgf.server
{
    public class HttpServer
    {
        private WebApplication app { get; set; }

        public Task Start(int port, bool isHttps, Action<HttpContext> handler)
        {
            var builder = WebApplication.CreateBuilder();
            builder.WebHost.UseKestrel(options =>
                {
                    // HTTP 
                    if (isHttps)
                    {
                        options.ListenAnyIP(port, builder => { builder.UseHttps(); });
                    }
                    else
                    {
                        options.ListenAnyIP(port);
                    }
                })
                .ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Error); })
                .UseNLog();

            app = builder.Build();
            app.Map("/game/{text}", (HttpContext context) => handler.Invoke(context));
            return app.StartAsync();
        }

        /// <summary>
        /// 停止
        /// </summary>
        public async Task Stop()
        {
            LogMgr.Info("停止http服务...");
            await app.StopAsync();
            app = null;
        }
    }
}